package edu.ucsd.cse110;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import edu.ucsd.cse110.model.Wod;

/**
 * Displays a list of WODs and returns the ID of the selected WOD.
 */
public class WodSelectionActivity extends ListActivity implements
		OnItemSelectedListener {
	private List<Wod> mWodList;
	private ListActivity mActivity;

	/**
	 * TODO: Need documentation.
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wod_selection);

		mActivity = this;

		// Loads the list of names of the benchmarks from resources.
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.benchmarks, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		// Sets up spinner.
		Spinner spinner = (Spinner) findViewById(R.id.spinner);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(this);

	}

	/**
	 * Updates the list of WODs to match the new WOD type.
	 */
	public void onItemSelected(AdapterView<?> parent, View view, int pos,
			long id) {
		// Retrieves a list of WODs by WOD type.
		LocalDatabaseManager database = new LocalDatabaseManager(mActivity);
		mWodList = database.getWodByType(Wod.Type.values()[pos]);
		database.close();

		// Updates the list adapter.
		List<String> names = new ArrayList<String>();

		for (Wod item : mWodList) {
			names.add(item.getName());
		}

		mActivity.setListAdapter(new ArrayAdapter<String>(mActivity,
				android.R.layout.simple_list_item_1, names));
	}

	/**
	 * Finishes this activity and returns the ID of the selected WOD.
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		// Gets the selected WOD.
		Wod item = mWodList.get(position);

		// Returns the ID of the selected WOD.
		Intent data = new Intent();
		data.putExtra("Id", item.getId());
		setResult(RESULT_OK, data);
		finish();
	}

	/**
	 * Does nothing when no change has been made to WOD type.
	 */
	public void onNothingSelected(AdapterView<?> parent) {
	}
}